<template>
	<view class="vip-master-view">
		<view class="clip-me"></view>
		<view class="vip-component">
			<view class="top-nav">
				<van-icon name="arrow-left" color="#081A2A" size="18" class="nav-back-icon" @click="goback" />
				<view class="title">兑换奖励</view>
			</view>
			<view class="main">
				<view class="day-num">
					<view class="label"> 待兑换天数：</view>
					<view class="value">{{ myVipRewardData.remainDay }}天</view>
				</view>
				
				<view class="day-child-action">
					<view class="exchange-day">
						<view class="exchange-title">兑换天数</view>
						<view class="day-options">
							<template v-for="(d, i) in dayDic" :key="i">
								<view class="day-item" :class="{'action': d.active}" @click="() => selectDay(i)">  
								  {{ d.value }} {{ d.unit }} 
								  <SelectedVue :visible="d.active" />  
								</view>
							</template>
						</view>
					</view>
					
					<view class="exchange-child">
						<view class="child-title">兑换小孩</view>
						<view class="child-options" v-for="(children, index) in students" :index="index" :key="index">
							<view class="child-item" :class="{'action': studentActive === index}" @click="() => selectStudent(index)">
								<view class="child-name">{{ children.username || children.nickName || children.name }}</view>
								<view class="option-time">
									<view class="label">现到期时间</view>
									<view class="time">{{ extractDate(children.expireDate)}}</view>
								</view>
								<view class="option-time">
									<view class="label">兑换后期时间</view>
									<view class="time">{{ addDaysToDate(children.expireDate, getSelectDay) }}</view>
								</view>
								<SelectedVue :visible="studentActive === index"/>
							</view>
						</view>
					</view>
					<view class="exchange-btn" @click="exchange">兑换</view>
				</view>
			</view>
		</view>
		
		<!-- <RegisterSucess :show="registerShow" :info="regInfo" @onOk="onOkReg" @onClose="close" v-if="registerShow" /> -->
		
		 <DialogSuccess :show="show" :info="sucessInfo" @onOk="onOk" v-if="show"/>
		<DialogError :show="errorShow" :info="errorInfo" @onOk="onErrorOk" @goVipPage="goVipPage" v-if="errorShow"/>
			<GlobalWebsocketNotice />
	</view>
</template>

<script setup lang="ts">
	import { computed, onMounted, ref } from 'vue'
	import SelectedVue from './selected.vue';
	import DialogSuccess from '@/components/customDialog/exchangeSuccess.vue'
	import DialogError from '@/components/customDialog/exchangeError.vue'
	import RegisterSucess from '@/components/customDialog/registerSuccess.vue'
	import GlobalWebsocketNotice from '@/components/globalWebsocketNotice/index.vue'
	import { urlHelp, timeFormatHelp } from '@/utils/index';
	import dayjs from "@/plugins/dayjs.js"
	import { setupWebSocket } from '@/utils/socket.js';
	// import { useVipStore} from "@/stores/useVip.js"
	// import {useStudentListStore} from '@/stores/useStudentList.js'
	import { vipServer, homeServer } from "@/common/index";
	import { useStudentListStore } from "@/stores/useStudentList.js"
	const studentStore = useStudentListStore();
	const curStud = ref(studentStore.currentStudent);
	const allStud  = ref(studentStore.students)
		
	// const vipStore = useVipStore();
	// const sutdentStore = useStudentListStore();
	// const myLotteryDraw = computed(() => vipStore.lotteryDraw) // 我抽奖抽中的物品
	// const students = computed(() => sutdentStore.students) // 所有的孩子
	
	const isVipExpire = computed(() =>timeFormatHelp.daysDifference(curStud.expireDate) <= 0) ; 
	
	const studentActive = ref(0);
	const selectStudent = (index: number) => {
		studentActive.value = index
	}
	// console.log('抽中的奖，以及所有的孩子', myLotteryDraw.value, students.value)
	
	function extractDate(dateTime: string): string {
	    return dayjs(dateTime).format('YYYY/MM/DD');
	}
	function addDaysToDate(date: string, days: number): string {
		const isVipExpire =  timeFormatHelp.daysDifference(date) <= 0; // true  vip 已经过期了，false: vip 没有过期
		if(isVipExpire){
			const futureDate = dayjs().add(days, 'day'); 
			return futureDate.format('YYYY/MM/DD');
		} else {
			return dayjs(date).add(days, 'day').format('YYYY/MM/DD');
		}
	}
	
	// 可以选哪几天
	const dayDic = ref([
		{
			value: 10,
			unit: '天',
			active: true
		},
		{
			value: 15,
			unit: '天',
			active: false
		},
		{
			value: 30,
			unit: '天',
			active: false
		}
	]);
	
	const getSelectDay = computed(() => {
		const { value } = dayDic.value.find(item => item?.active)
		return value
	})
	const selectDay = (i: number) =>{
		dayDic.value?.forEach((atom, index) => {
			if(index === i){
				atom.active = true
			} else {
				atom.active = false
			}
		})
		console.log('dayDic.value', dayDic.value)
	}
	
	// 我的奖池
	const myVipRewardData = ref({});
	// 获取奖品列表
	const myVipReward = async () => {
		try{
			const { data, status } = await vipServer.myVipReward()
			if(status === '200'){
				myVipRewardData.value = data
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	const students = ref([]);
	// 获取学生信息
	const queryStudentList = async () => {
		try{
			const {data, status} = await homeServer.studentList()
			if(status === "200"){
				const sts = data?.map(item => urlHelp.imgAddPrefix(item, 'imageUrl')) || [];
				console.log('sts-----学生', sts)
				students.value = sts
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
		
	onMounted(() => {
		myVipReward()
		queryStudentList()
	})
	
	
	const show = ref(false)
	const sucessInfo = ref({
		name:"", // 张三
		day:"", //  10天vip 兑换成功
		time:"" // 到期时间 2024年9月2日
	})
	 const onOk = () => {
		myVipReward()
		queryStudentList()
		show.value = false
		// setTimeout(() => {
		// 	uni.navigateTo({
		// 		url: "/pagesD/jackpot/index"
		// 	})
		// }, 1500)
	 }
	 
	const errorShow = ref(false);
	const errorInfo = ref({
		title:"兑换失败，剩余天数不足",
		more:"查看领vip攻略>>",
		href:""
	})
	const onErrorOk = () => {
		errorShow.value = false;
	}
	
	const goVipPage = () => {
		errorShow.value = false;
		// uni.switchTab({
		// 	url: "/pages/tabbar/vip/index"
		// })
	}

	
	
	const registerShow = ref(true)
	const regInfo = ref({
		title:"提示",
		friend:"150***111",
		worth:"1元的2天vip会员和10积分",
		okTxt: '领取VIP到奖池',
		href: null,
		isFirst: false
	})
	
	const onOkReg = () => {
		console.log("关闭弹窗")
		registerShow.value = false
		uni.navigateTo({
			url:"/pagesD/jackpot/index"
		})
	}
	const close = () => {
		registerShow.value = false
	}
	
	const goback = () => {
		uni.switchTab({
			url:"/pages/tabbar/vip/index"
		})
	}
	
	const exchangeIng = ref(false); // false： 可以开始兑奖，true： 已经点击了兑奖还没返回结果,此时不能再次点击兑奖
	// 奖励兑换
	const exchange = async () => {
		if(exchangeIng.value){
			uni.showToast({
				title:"正在兑奖中，请稍后再兑",
				icon:"none",
				duration:1000
			})
			return;
		}
		exchangeIng.value = true
		console.log('myVipRewardData.value', myVipRewardData.value, getSelectDay.value)
		if(myVipRewardData.value?.remainDay < getSelectDay.value || !myVipRewardData.value?.remainDay ){
			uni.showToast({
				title:"您待兑换天数不足！",
				icon:"none"
			})
			exchangeIng.value = false
			return;
		}
		try{
			const { id, username, nickName, name, expireDate } = students.value.find((_, i) => i === studentActive.value)
			const params = {
				studentId: id,
				exchangeCount: getSelectDay.value
			}
			const { status, data, message } = await vipServer.rewardExchange(params)
			if(status === '200'){
				console.log('data', data)
				show.value = true;
				sucessInfo.value = {
					name: username ||  nickName || name, // 张三
					day: `${getSelectDay.value}天VIP 兑换成功`,  //  10天vip 兑换成功
					time: `到期时间 ${addDaysToDate(expireDate, getSelectDay.value)}` // 到期时间 2024年9月2日
				}
				setTimeout(() => {
					exchangeIng.value = false
				}, 2000)
			} else {
				errorInfo.value.title = message || '兑换失败，剩余天数不足'
				errorShow.value = true
				exchangeIng.value = false
			}
		}catch(e){
			exchangeIng.value = false
			console.log(e)
			//TODO handle the exception
		}
	}
	
</script>
<style>
	page {
		background-color: #eff8fd;
	}
</style>
<style lang="scss" scoped>
	.top-nav {
		width: 100%;
		height: 60upx;
		padding-top: 100upx;
		text-align: center;
		position: fixed;
		top: 0;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		line-height: 60upx;

		// background-color: #ccc;
		.nav-back-icon {
			position: absolute;
			left: 20upx;
			z-index: 2;
		}

		.title {
			color: #081A2A;
			font-weight: 600;
			font-size: 36upx;
			position: absolute;
			left: 0;
			right: 0;
			margin: 0 auto;
		}
	}
</style>
<style lang="scss">
	.vip-master-view {
		background-size: cover;
		background-position: center;
		min-width: 100vw;
		min-height: 100vh;
		position: relative;
		.clip-me{
				  width: 600upx;
				  height: 600upx;
				  right: 0;
				  top: 0;
				  background-color: #e9fbfc;
				  backdrop-filter: blur(5upx);
				  box-shadow: 2upx 5upx 5upx rgba(179, 241, 215, 0.1);
					z-index: -1;
				   position: absolute; /* absolute or fixed positioning required */
				   // clip: rect(110px, 160px, 170px, 60px); /* or "auto" */
				clip-path: polygon(16% 38%, 10% 23%, 35% 6%, 70% 2%, 100% 0, 100% 15%, 100% 85%, 100% 100%, 85% 100%, 0 100%, 21% 68%, 25% 51%);
		}

	}
</style>
<style lang="scss">
	.vip-component {
		position: absolute;
		background-color: red;
		min-width: 100vw;
		min-height: 100vh;
		background: rgba(255, 255, 255, 0.3);
		/* 半透明的白色背景 */
		// border-radius: 15px;
		// padding: 20px;
		text-align: center;
		// backdrop-filter: blur(10px);
		/* 应用模糊效果 */
		// -webkit-backdrop-filter: blur(10px);
		/* 兼容 Webkit 内核的浏览器 */
		// box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */

		.main {
			position: absolute;
			top: 220upx;
			padding: 0 20upx;
			width: calc(100% - 40upx);
		
		.day-num{
			display: flex;
			justify-content: space-between;
			align-items: center;
			// width: calc(100% - 80upx);
			padding: 20upx;
			height: 112upx;
			background: #FFFFFF;
			border-radius: 12upx;
			margin-bottom: 20upx;
			.label{
				font-family: PingFang SC, PingFang SC;
				font-weight: 600;
				font-size: 28upx;
				color: #081A2A;
				text-align: left;
				font-style: normal;
				text-transform: none;
			}
			.value{
				font-family: PingFang SC, PingFang SC;
				font-weight: 600;
				font-size:28upx;
				color: #2BC888;
				text-align: right;
				font-style: normal;
				text-transform: none;
			}
		}


		}

	}
</style>


<style lang="scss" scoped>
	.day-child-action{
		min-height: 888upx;
		background: #FFFFFF;
		border-radius: 12upx;
		.exchange-day{
			margin-bottom: 40upx;
			padding: 20upx;
			.exchange-title{
				margin-bottom: 24upx;
				font-weight: 600;
				font-size: 28upx;
				color: #081A2A;
				text-align: left;
			}
			.day-options{
				 display: grid;
				  grid-template-columns: repeat(3, 1fr);
				  grid-template-rows: repeat(1, 110upx); /* 每个方块高度为204upx */
				  gap: 20upx; /* 设置列之间的间隔 */
				.day-item{
					background: #F2F4F5;
					border-radius: 8upx;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 32upx;
					color: #081A2A;
					font-weight: 600;
				}
				.action{
					box-sizing: border-box;
					background: rgba(43,200,136,0.1);
					border: 4upx solid #2BC888;
					color: #2BC888;
					position: relative;
				}
			}
		}
		.exchange-child{
			margin-bottom: 40upx;
			padding: 20upx;
			.child-title{
				margin-bottom: 24upx;
				font-weight: 600;
				font-size: 28upx;
				color: #081A2A;
				text-align: left;
			}
			.child-options{
				display: flex;
				flex-direction: column;
				.child-item{
					height: 130upx;
					background: #F2F4F5;
					border-radius: 8upx;
					margin-bottom: 12upx;
					box-sizing: border-box;
					
					display: grid;
					grid-template-columns: repeat(3, 1fr);
					 // grid-template-rows: repeat(3, 65upx); /* 每个方块高度为204upx */
					 // gap: 20upx; /* 设置列之间的间隔 */
					 
					.child-name{
						font-weight: 600;
						font-size: 32upx;
						color: #081A2A;
						display: flex;
						align-items: center;
						justify-content: center;
					}
					.option-time{
						display: flex;
						align-items: center;
						justify-content: center;
						flex-direction: column;
						.label{
							font-weight: 400;
							font-size: 24upx;
							color: #999999;
							text-align: left;
							font-style: normal;
							text-transform: none;
						}
						.time{
							font-weight: 400;
							font-size: 24upx;
							color: #081A2A;
							text-align: left;
							font-style: normal;
							text-transform: none;
							margin-top: 10upx;
						}
					}
				}
				.action{
					box-sizing: border-box;
					background: rgba(43,200,136,0.1);
					border-radius: 8upx;
					border: 4upx solid #2BC888;
					position: relative;
					.child-name{
						color: #2BC888;
					}
					.option-time{
						.label{
							color: #2BC888;
						}
						.time{
							color: #2BC888;
						}
					}
				}
			}
		}
	}
	
	
	
	.exchange-btn{
		display: flex;
		align-items: center;
		justify-content: center;
		width: 90%;
		margin: 0 auto;
		height: 108upx;
		background: #2BC888;
		border-radius: 54upx;
		font-weight: 600;
		font-size: 32upx;
		color: #FFFFFF;
	}
</style>


